package com.chen.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dashscope.common.Message;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.bean.entity.MessageEntity;
import com.chen.dao.MessageMapper;
import com.chen.service.MessageService;
import com.chen.util.CacheUtils;
import com.chen.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    private CacheUtils cacheUtils;

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 异步保存消息到Redis
     * @param key Redis中的键，用于存储消息列表 包含用户id及对话编号
     * @param messageList 要保存的消息列表，不包含本次系统返回的消息
     */
    @Override
    @Async("saveMessageToRedis")
    public void saveMessageToRedis(String key, List<MessageEntity> messageList) {
        //删除并重新设置缓存
        cacheUtils.deleteAndSetCacheList(key,messageList);
    }
    /**
     * 根据对话编号查询消息实体列表
     */
    @Override
    public List<MessageEntity> queryByDialogNumber(String dialogNumber) {
        LambdaQueryWrapper<MessageEntity> lqw = new LambdaQueryWrapper<MessageEntity>();
        lqw.eq(MessageEntity::getDialogNumber,dialogNumber).orderByAsc(MessageEntity::getCreateTime);
        return messageMapper.selectList(lqw);
    }

    /**
     * 批量插入
     */
    @Override
    public void batchSave(List<MessageEntity> cacheList) {
        messageMapper.insert(cacheList);
    }

    /**
     * 将消息实体列表转换为Message列表
     * @param messageList
     * @return
     */
    public List<Message> buildMessageList(List<MessageEntity> messageList) {
        if (CollectionUtil.isEmpty(messageList)){
            return new ArrayList<>();
        }
        return messageList.stream().map(entity ->
                Message.builder().role(entity.getRole()).content(entity.getContent()).build()).collect(Collectors.toList());
    }

    @Override
    public MessageEntity buildMessageEntity(String dialogNumber, String role, String content) {
        MessageEntity userEntity = new MessageEntity();
        userEntity.setDialogNumber(dialogNumber);
        userEntity.setRole(role);
        userEntity.setContent(content);
        userEntity.setCreateTime(new Date());
        userEntity.setUpdateTime(new Date());
        return userEntity;
    }
}
